﻿/**
import { Window } from './android-proxy';
 * 创建 android 基座所使用后退事件
 */
declare const window:any;

export default class AndroidGoBackHandlerListener {
  constructor() {
    this.createAndroidElementToast()
    /**
     * 绑定到window变量
     */
    window._androidGoBackBySystemButton = this.androidGoBackBySystemButton
  }
  androidSystemToastTimeoutId = 0

  /**
   * create toast
   */
  createAndroidElementToast = () => {
    const el = document.querySelector('body .android-system-toast-box')
    if (el) {
      //如果存在，则退出
      return
    }
    //创建
    const toastHTML: string = `<!-- android toast -->
        <div class="android-system-toast-box"
            style="justify-content: center;
              width: 100%;
              position: absolute;
              bottom: 100px;
              display: none;
              box-sizing: border-box;
              padding: 0px 10%;">
          <div class="label" id="android-text-info" 
            style="
              background: #000;
              width: auto;
              color: #fff;
              padding: 10px 22px;
              text-align: left;
              font-size: 12px;
              border-radius: 6px;
              box-shadow: 2px 2px 1px #cfcfcf;
              line-height: 20px;">
            </div>
        </div>
      `
    //在body节点追加
    ;(document.querySelector('body') as any).innerHTML += toastHTML
  }
  /**
   * toast 显示方法
   * @param msg
   */
  androidSystemToast = (msg: string) => {
    clearTimeout(this.androidSystemToastTimeoutId)
    const el = document.querySelector('.android-system-toast-box #android-text-info') as any
    el.innerText = msg
    this.androidSystemToastTimeoutId = setTimeout(() => {
      clearTimeout(this.androidSystemToastTimeoutId)
      const elBox = document.querySelector('.android-system-toast-box') as any
      elBox.style.display = 'flex'
      this.androidSystemToastTimeoutId = setTimeout(() => {
        elBox.style.display = 'none'
        clearTimeout(this.androidSystemToastTimeoutId)
      }, 2000)
    }, 200)
  }
  /**
   * 点击返回按钮，返回页面
   */
  androidGoBackBySystemButton = (go: number = -1) => {
    if (go === 0) {
      window.location.reload()
      return true
    }
    const position = window.history.state.position + go
    if (position > window.history.length) {
      this.androidSystemToast('已经到达最顶层！')
      return false
    }
    if (position < 0) {
      this.androidSystemToast('已经退到最低层！')
      return false
    }
    window.history.go(go)
    return true
  }
}
 
